import { ElMessage, ElMessageBox, ElMessageBoxOptions } from "element-plus";
import { VNode, defineComponent, h } from "vue";

type TipType = "info" | "success" | "error" | "warning" | "none";

interface IElMessageBoxProps {
    /** 正文 */
    text: string | VNode | (() => VNode),
    /** 弹出类型 */
    type: TipType,
    /** 提示类型 */
    tipType: "alert" | "confirm",
    /** 来自提示 */
    from: string,
    /** 顶部标题 */
    topTitle?: string,
    /** 确认文字 */
    confirmText?: string,
    /** 取消文字 */
    cancelText?: string,
    /** 弹窗自动确定延迟 传入秒s */
    durationSeconds?: number,
    /** 取消前事件 */
    beforeClose?: (next: () => void) => void,
    /** element扩展配置 */
    options?: ElMessageBoxOptions
}

async function _elMessageBox(params: IElMessageBoxProps) {

    let { text, type, tipType, topTitle, from, confirmText, cancelText, beforeClose, options } = params;

    if (topTitle) {
        // topTitle += ` - ${from}`
    }

    if (!options) {
        options = {}
    }
    let title = ""
    // switch (type) {
    //     case "info":
    //         title = `提示 - ${from}`
    //         break;
    //     case "success":
    //         title = `成功 - ${from}`
    //         break;
    //     case "error":
    //         title = `错误 - ${from}`
    //         break;
    //     case "warning":
    //         title = `警告 - ${from}`
    //         break;
    //     default:
    //         break;
    // }

    if (typeof text === "function") {
        const textDiv = text
        text = h(defineComponent({
            render: textDiv as any
        }))
    }

    let className = "";


    if (tipType === "alert") {
        let timer: any = null;
        if (params.durationSeconds && params.durationSeconds > 0) {
            className = getRandomClassName();

            let duration = params.durationSeconds;

            function run() {
                const el = document.querySelector(`.${className}`)
                if (el) {
                    el.innerHTML = `${confirmText ? confirmText : '确定'} (${Math.ceil(duration)})`

                    if (duration <= 0) {
                        (el as any).click();
                    } else {
                        duration -= 1;
                    }
                }
            }

            setTimeout(run, 0)

            timer = setInterval(run, 1000)
        }


        await ElMessageBox.alert(text, topTitle ?? title, {
            confirmButtonText: confirmText ?? "确定",
            type: type === "none" ? undefined : type,
            draggable: true,
            autofocus: true,
            confirmButtonClass: className,
            beforeClose: (action, __, done) => {

                if (action === "confirm" && typeof beforeClose !== "undefined") {
                    beforeClose(done)
                } else {
                    done()
                }
                clearInterval(timer);
            },
            ...options
        })
    } else if (tipType === "confirm") {
        let res = await ElMessageBox.confirm(text, topTitle ?? title, {
            confirmButtonText: confirmText ?? "确定",
            cancelButtonText: cancelText ?? "取消",
            autofocus: true,
            type: type === "none" ? undefined : type,
            draggable: true,
            beforeClose: (action, __, done) => {
                if (action === "confirm" && typeof beforeClose !== "undefined") {
                    beforeClose(done)
                } else {
                    done()
                }
            },
            ...options
        })

    }
}

/** 弹出框alert入参 */
interface ILdAlertParams {
    text: string | VNode | (() => VNode),
    type: TipType,
    topTitle?: string,
    confirmText?: string,
    cancelText?: string,
    durationSeconds?: number,
    beforeClose?: (next: () => void) => void,
    options?: ElMessageBoxOptions
}

/**
 * 前端弹出框
 * @param params 弹出入参
 */
export async function $alert(params: ILdAlertParams) {
    await _elMessageBox({
        ...params,
        tipType: "alert",
        from: `[来自Web]`
    })
}

/**
 * 后端弹出提示
 * @param params 弹出入参
 */
export async function $alertApi(params: ILdAlertParams) {
    await _elMessageBox({
        ...params,
        tipType: "alert",
        from: `[来自Api]`
    })
}

/**
 * 前端提示确认取消框
 * @param params 弹出入参
 */
export async function $confirm(params: ILdAlertParams) {
    await _elMessageBox({
        ...params,
        tipType: 'confirm',
        from: `[来自Web]`
    })
};

/**
 * 后端提示确认取消框
 * @param params 弹出入参
 */
export async function $confirmApi(params: ILdAlertParams) {
    await _elMessageBox({
        ...params,
        tipType: 'confirm',
        from: `[来自Api]`
    })
};

/** 提示类型 */
type TMessage = 'error' | 'info' | 'success' | 'warning';

function _showWebMessage(type: TMessage, text: string, desc?: string, duration = 3000) {

    ElMessage({
        type,
        message: text,
        duration,
        showClose: false,
    })
}

function _showApiMessage(type: TMessage, text: string, desc?: string, duration = 3000) {
    ElMessage({
        type,
        message: text,
        duration,
        showClose: false,
    })
}

/**
 * 前端消息提示
 */
export const $message = {
    /** 异常 */
    error(text: string, desc?: string, duration?: number) {
        _showWebMessage("error", text, desc, duration)
    },
    /** 信息 */
    info(text: string, desc?: string, duration?: number) {
        _showWebMessage("info", text, desc, duration)
    },
    /** 成功 */
    success(text: string, desc?: string, duration?: number) {
        _showWebMessage("success", text, desc, duration)
    },
    /** 警告 */
    warning(text: string, desc?: string, duration?: number) {
        _showWebMessage("warning", text, desc, duration)
    },
};

/**
 * 后端消息提示
 */
export const $messageApi = {
    /** 异常 */
    error(text: string, desc?: string, duration?: number) {
        _showApiMessage("error", text, desc, duration)
    },
    /** 信息 */
    info(text: string, desc?: string, duration?: number) {
        _showApiMessage("info", text, desc, duration)
    },
    /** 成功 */
    success(text: string, desc?: string, duration?: number) {
        _showApiMessage("success", text, desc, duration)
    },
    /** 警告 */
    warning(text: string, desc?: string, duration?: number) {
        _showApiMessage("warning", text, desc, duration)
    },
};

export const $toast = $message;

export const $toastApi = $messageApi;

/** class前缀 */
const classFix = "el_alert_but";

function getRandomClassName(): string {
    return classFix + Math.floor(1000 + Math.random() * 9000);
}